package com.zzyl.nursing.service.impl;

import java.nio.file.WatchService;
import java.util.List;

import cn.hutool.core.collection.ListUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.Arrays;
import java.util.Map;
import java.util.Random;

/**
 * 老人家属Service业务层处理
 *
 * @author zxw
 * @date 2025-10-16
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService {
    @Autowired
    private FamilyMemberMapper familyMemberMapper;

    @Autowired
    private WeChatServiceImpl weChatService;
   @Autowired
   private  TokenService tokenService;
    @Override
    public LoginVo login(UserLoginRequestDto dto) {
        //1.先获取 opeid
        String openid = weChatService.getopenid(dto.getCode());
        //2.根据openid 查询家属
        LambdaUpdateWrapper<FamilyMember> queryWrapper = new LambdaUpdateWrapper<>();
        queryWrapper.eq(FamilyMember::getOpenId, openid);
        FamilyMember familyMember = this.getOne(queryWrapper);
        //3.调用微信的接口获取用户的手机号
        String phone = weChatService.getphone(dto.getPhoneCode());
        //4.如果查不到 新增
        if (familyMember == null) {
            familyMember = new FamilyMember();
            familyMember.setPhone(phone);
            String nickname =DEFAULT_NICKNAME_PREFIX.get(new Random().nextInt(DEFAULT_NICKNAME_PREFIX.size()+1)) + phone.substring(7);
            familyMember.setName(nickname);
            familyMember.setOpenId(openid);
            this.save(familyMember);
        } else {
            //5.判断手机号是否有变化
            if (!familyMember.getPhone().equals(phone)){
                familyMember.setPhone(phone);
                this.updateById(familyMember);
            }
        }
        //6. 生成token
       Map<String,Object> map =Map.of("id",familyMember.getId());
        String token = tokenService.createToken(map);
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setNickName(familyMember.getName());
        return loginVo;
    }
    static List<String> DEFAULT_NICKNAME_PREFIX = ListUtil.of("生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝"
    );
}
